﻿using System;
using YEA.Infrastructure.Gateway;
using YEA.Infrastructure.Gateway.Converter;
using YEA.Utilities.Logging;
using YEA.Utilities.Logging.Converter;

namespace YEA.Monitor.LogManager
{
    public class MessageHandler : IMessageConsumer, IDisposable
    {
        private bool disposed;
        public MessageHandler()
        {
            log4net.Config.XmlConfigurator.Configure();
            //logger = log4net.LogManager.GetLogger("defaultLogger");

            disposed = false;
        }
        ~MessageHandler()
        {
            Dispose(false);
        }
        public void ConsumeMessage(Message message, RabbitMQ.Client.IModel channel, DeliveryHeader header)
        {
            var logEntry = MessageToStringConverter.Convert(message);
            LogType logLevel = (LogType)message.Properties.Headers[LogPropertiesStandards.LogLevelPropertyName];
            var logName = string.IsNullOrWhiteSpace(message.RoutingKey) ? "noNameLog" : message.RoutingKey;
            var logger = Logger.Get(logName);
            write(logLevel, logEntry, logger);
            channel.BasicAck(header.DeliveryTag, false);
        }
        protected void write(LogType level, string message, log4net.ILog logger)
        {
            switch (level)
            {
                case LogType.Debug: logger.DebugFormat(message);
                    break;
                case LogType.Error: logger.ErrorFormat(message);
                    break;
                case LogType.Fatal: logger.FatalFormat(message);
                    break;
                case LogType.Information: logger.InfoFormat(message);
                    break;
                case LogType.Warning: logger.WarnFormat(message);
                    break;
            }
        }
        public void Dispose()
        {
            Dispose(true);
            GC.SuppressFinalize(this);
        }
        private void Dispose(bool disposing)
        {
            if( !disposed)
                log4net.LogManager.Shutdown();
            disposed = true;
        }

    }
}
